package com.foreverwin.mes.so.controller;

import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Item;
import com.foreverwin.mes.meapi.model.Operation;
import com.foreverwin.mes.meapi.service.ItemService;
import com.foreverwin.mes.meapi.service.OperationService;
import com.foreverwin.mes.so.dto.CycleTimeDeleteCmd;
import com.foreverwin.mes.so.dto.CycleTimeDeleteReq;
import com.foreverwin.mes.so.model.CycleTimeConfig;
import com.foreverwin.mes.so.model.CycleTimeConfigView;
import com.foreverwin.mes.so.service.CycleTimeConfigService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author syngna
 * @since 2018-11-12
 */
@RestController
@RequestMapping("/cycleTimeConfigs")
public class CycleTimeConfigController {
    private final Logger logger = LoggerFactory.getLogger(CycleTimeConfigController.class);

    @Autowired
    public CycleTimeConfigService cycleTimeConfigService;

    @Autowired
    public ItemService itemService;

    @Autowired
    public OperationService operationService;

    /**
     * 根据非空条件查询
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getCycleTimeConfigList(CycleTimeConfigView cycleTimeConfigView) {
        List<CycleTimeConfigView> result;
        String site = CommonMethods.getSite();
        try {
            cycleTimeConfigView.setSite(site);
            result = cycleTimeConfigService.selectKeySelectiveList(cycleTimeConfigView);
        } catch (Exception e) {
            logger.error("getCycleTimeConfigList -=- {}", e.toString());
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     *
     * @param cycleTimeConfigView 传递的实体
     * @return null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult cycleTimeConfigSave(@RequestBody CycleTimeConfigView cycleTimeConfigView) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        String item = cycleTimeConfigView.getItem();
        String itemRevision = cycleTimeConfigView.getItemRevision();
        String operation = cycleTimeConfigView.getOperation();
        String resrce = cycleTimeConfigView.getResrce();
        String cycleTime = cycleTimeConfigView.getCycleTime();
        String needSoPlan = cycleTimeConfigView.getNeedSoPlan();
        CycleTimeConfig cycleTimeConfig = new CycleTimeConfig();

        int count = 0;
        try {
            List<Operation> currentOperationList = operationService.selectList(new EntityWrapper<Operation>()
                    .eq("SITE", site)
                    .eq("OPERATION", operation)
                    .eq("CURRENT_REVISION", "true"));

            if (currentOperationList == null || currentOperationList.size() == 0) {
                throw BusinessException.build("工序【" + operation + "】当前版本不存在");
            }
            String resourceType = StringUtils.trimHandle(currentOperationList.get(0).getResourceTypeBo());
            if (StringUtils.isBlank(itemRevision)) {
                List<Item> currentItemList = itemService.selectList(new EntityWrapper<Item>()
                        .eq("SITE", site)
                        .eq("ITEM", item)
                        .eq("CURRENT_REVISION", "true"));
                if (currentItemList == null || currentItemList.size() == 0) {
                    throw BusinessException.build("物料【" + item + "】当前版本不存在");
                }
                itemRevision = currentItemList.get(0).getRevision();
            } else if(itemService.selectById(StringUtils.genHandle(HandleBOConstants.ITEM_BO, site, item, itemRevision)) == null){
                throw BusinessException.build("物料【" + item + "】版本【"+ itemRevision +"】不存在");
            }
            String itemBo = StringUtils.genHandle(HandleBOConstants.ITEM_BO, site, item, itemRevision);
            List<CycleTimeConfig> existsList = cycleTimeConfigService.selectList(
                    new EntityWrapper<CycleTimeConfig>()
                            .eq(CycleTimeConfig.ITEM_BO, itemBo)
                            .eq(CycleTimeConfig.OPERATION_BO, StringUtils.genHandle(HandleBOConstants.OPERATION_BO, site, operation, "#"))
                            .eq(CycleTimeConfig.RESRCE, resrce));
            if(existsList != null && existsList.size() > 0) {
                String key = itemBo + "," + StringUtils.genHandle(HandleBOConstants.OPERATION_BO, site, operation, "#") + "," + resrce;
                throw BusinessException.build("重复键值 '" + key + "'");
            }
            cycleTimeConfig.setSite(site);
            cycleTimeConfig.setItemBo(StringUtils.genHandle(HandleBOConstants.ITEM_BO, site, item, itemRevision));
            cycleTimeConfig.setOperationBo(StringUtils.genHandle(HandleBOConstants.OPERATION_BO, site, operation, "#"));
            cycleTimeConfig.setResrce(resrce);
            cycleTimeConfig.setResourceType(resourceType);
            cycleTimeConfig.setCycleTime(cycleTime);
            cycleTimeConfig.setNeedSoPlan(needSoPlan);
            cycleTimeConfig.setStatus("Y");
            cycleTimeConfig.setCreatedDateTime(new Date());
            cycleTimeConfig.setModifiedDateTime(new Date());
            cycleTimeConfig.setCreator(user);
            cycleTimeConfig.setUpdater(user);
            //count = cycleTimeConfigService.insert(cycleTimeConfig) ? 1 : 0;
            count = cycleTimeConfigService.insert(cycleTimeConfig) ? 1 : 0;
        } catch (Exception e) {
            logger.error("cycleTimeConfigSave -=- {}", e.toString());
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(count == 0 ? null : cycleTimeConfigView);
    }

    /**
     * 修改公用
     *
     * @param cycleTimeConfigView 传递的实体
     * @return null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_update")
    public AjaxResult cycleTimeConfigModify(@RequestBody CycleTimeConfigView cycleTimeConfigView) {
        CycleTimeConfig cycleTimeConfig = new CycleTimeConfig();
        String user = CommonMethods.getUser();
        try {
            cycleTimeConfig.setHandle(cycleTimeConfigView.getHandle());
            cycleTimeConfig.setCycleTime(cycleTimeConfigView.getCycleTime());
            cycleTimeConfig.setNeedSoPlan(cycleTimeConfigView.getNeedSoPlan());
            cycleTimeConfig.setModifiedDateTime(cycleTimeConfigView.getModifiedDateTime());//乐观锁
            cycleTimeConfig.setUpdater(user);
            cycleTimeConfigService.updateById(cycleTimeConfig);
        } catch (Exception e) {
            logger.error("cycleTimeConfigSave -=- {}", e.toString());
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(cycleTimeConfigView);
    }

    /**
     * 根据id删除对象，逻辑删除
     *
     * @param cycleTimeDeleteCmd 删除所需实体参数
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_delete")
    public AjaxResult cycleTimeConfigDelete(@RequestBody CycleTimeDeleteCmd cycleTimeDeleteCmd) {
        String user = CommonMethods.getUser();
        try {
            CycleTimeDeleteReq cycleTimeDeleteReq = new CycleTimeDeleteReq();
            cycleTimeDeleteReq.setHandle(cycleTimeDeleteCmd.getHandle());
            cycleTimeDeleteReq.setModifiedDateTime(cycleTimeDeleteCmd.getModifiedDateTime());
            cycleTimeDeleteReq.setUser(user);
            cycleTimeConfigService.deleteById(cycleTimeDeleteReq);
        } catch (Exception e) {
            logger.error("cycleTimeConfigDelete -=- {}", e.toString());
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success("delete success!");
    }

    /**
     * 批量删除对象，逻辑删除
     *
     * @param cycleTimeDeleteCmds 删除所需实体列表参数
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult deleteBatchIds(@RequestBody List<CycleTimeDeleteCmd> cycleTimeDeleteCmds) {
        String user = CommonMethods.getUser();
        try {
            List<CycleTimeDeleteReq> list = new ArrayList<CycleTimeDeleteReq>();
            for (CycleTimeDeleteCmd cmd : cycleTimeDeleteCmds) {
                CycleTimeDeleteReq cycleTimeDeleteReq = new CycleTimeDeleteReq();
                cycleTimeDeleteReq.setHandle(cmd.getHandle());
                cycleTimeDeleteReq.setModifiedDateTime(cmd.getModifiedDateTime());
                cycleTimeDeleteReq.setUser(user);
                list.add(cycleTimeDeleteReq);
            }
            cycleTimeConfigService.deleteBatchById(list);
        } catch (Exception e) {
            logger.error("cycleTimeConfigBatchDelete -=- {}", e.toString());
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success("delete successful!");
    }
}